package ru.arriah.servicedesk.ejb;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;

import javax.ejb.EJBException;
import javax.ejb.SessionContext;
import javax.sql.DataSource;

import ru.arriah.common.ejb.GenericSessionBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.help.DbUtils;
import ru.arriah.servicedesk.help.Utils;


public class GroupManager extends GenericSessionBean {
   protected DataSource dataSource;

   public GroupManager() {
      super();
      dataSource = null;
   }

   public void setSessionContext(
      SessionContext sessionContext
   ) throws EJBException, RemoteException {
      super.setSessionContext(sessionContext);

      try {
         this.dataSource = Utils.getDataSource();
      } catch (Exception e) {
         handleException(e, "setSessionContext");
         throw new EJBException(e);
      }
   }


   
   public Collection<GroupBean> selectGroups() {
      Connection connection = null;
      PreparedStatement preparedStatement = null;
      ResultSet resultSet = null;

      try {
         ArrayList<GroupBean> groupsList = new ArrayList<GroupBean>();

         connection = dataSource.getConnection();
         preparedStatement = connection.prepareStatement(
            "SELECT * FROM `group`"
         );

         resultSet = preparedStatement.executeQuery();

         while (resultSet.next()) {
            GroupBean groupBean = new GroupBean();
            groupBean.setId(resultSet.getInt("id"));
            groupBean.setName(resultSet.getString("group_name"));
            groupsList.add(groupBean);
         }

         return groupsList;
      } catch (Exception e) {
         handleException(e, "selectGroups");
         throw new EJBException(e);
      } finally {
         DbUtils.closeQuietly(connection, preparedStatement, resultSet);
      }
   }
}